package com.cx.base.day19_thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @Author: robert.song
 * @Date: Created in 2021/11/26
 */
public class Thread_13_7_原子性_原子累加器 {
    public static void main(String[] args) {
        demo(() -> new AtomicLong(0), adder -> adder.getAndIncrement());
    }

    /**
     * @param adderSupplier 提供累加器对象
     * @param action        执行累加器指令
     * @param <T>
     */
    private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
        T adder = adderSupplier.get();
        List<Thread> ts = new ArrayList<>();
//        四个线程，每个累加50万
        for (int i = 0; i < 4; i++) {
            ts.add(new Thread(() -> {
                for (int j = 0; j < 500000; j++) {
                    action.accept(adder);
                }
            }));
        }
        long start = System.nanoTime();
        try {
            ts.forEach(t -> t.start());
            long end = System.nanoTime();
            Thread.sleep(1000);
            System.out.println(adder + " cost:" + (end - start) + "纳秒");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
